package cn.boysoft.generate.model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public abstract class Model {
	private String templateName;
	private String templateDirectory;
	private String targetFile;
	private List<String> importClasses;
	
	public String getTemplateName() {
		return templateName;
	}
	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}
	public String getTemplateDirectory() {
		return templateDirectory;
	}
	public void setTemplateDirectory(String templateDirectory) {
		this.templateDirectory = templateDirectory;
	}
	
	public List<String> getImportClasses() {
		return importClasses;
	}
	public void setImportClasses(List<String> importClasses) {
		this.importClasses = importClasses;
	}
	
	public String getTargetFile() {
		return targetFile;
	}
	public void setTargetFile(String targetFile) {
		this.targetFile = targetFile;
	}
	
	abstract Model fillDataToModel(Class entityClass);
	
	public void generateFile(Class entityClass) throws IOException, TemplateException{
		fillDataToModel(entityClass);
		Configuration cfg = new Configuration();
        cfg.setDirectoryForTemplateLoading(new File(templateDirectory));
        Template t = null;
        Writer out =null;
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("root", this);
        t = cfg.getTemplate(templateName);
        out = new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8");
        t.process(root, out);
        out.flush();
        out.close(); 
	}
	
}
